package com.wx.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wx.common.utils.ImagePathUtil;
import com.wx.mapper.CartMapper;
import com.wx.pojo.Cart;
import com.wx.service.CartService;
/**
 *购物车
 */
@Service
public class CartServiceImpl implements CartService {

	@Autowired
	private CartMapper cartMapper;
	/**
	 * 加入购物车
	 */
	@Override
	public String addCart(Cart cart) {
		//1.先查询购物车里面是否存在该用户加入的商品
		Cart findCart=cartMapper.findCartBySourceIdAndByUserId(cart);
		//判断是否已经存在
		System.out.println("findCart: "+findCart);
		if(findCart!=null) {
			//存在之后，购物车攒在的数量和新加入的数量
			cart.setSourceCount(findCart.getSourceCount()+cart.getSourceCount());
			//计算单个商品总价
			Double sourceFeeAll =findCart.getSourceFee()+cart.getSourceFee();
			cart.setSourceFee(findCart.getSourceFee()+cart.getSourceFee());
			cart.setCartId(findCart.getCartId());
			cartMapper.updateCart(cart);
			//判断是否成功存入数据库
			Cart cartSourceFee=cartMapper.findCartByCartId(findCart.getCartId());
			if(cartSourceFee.getSourceFee().equals(sourceFeeAll)) {
				return "update";
			}else {
				return "failUpdate";
			}			
		}else{
			//购物车不存在，新增购物车数据
			cartMapper.insertCart(cart);
			System.out.println("cartId: "+cart.getCartId());
			if(cart.getCartId()!=null) {
				return "insert";
			}
			return "failUpdate";
			
		}
			
		
	}
	/**
	 * 查询购物信息通过用户id
	 * 查询用户加入的购物车信息
	 */
	@Override
	public List<Cart> findCartByUserId(String userId) {
		List<Cart> cartList=cartMapper.findCartByUserId(userId);
		if(!cartList.isEmpty() && cartList.size()>0) {
			for (Cart cart : cartList) {
				if(cart.getSourceImage()!=null || cart.getSourceImage()!=null) {
					cart.setSourceImage(ImagePathUtil.firstSourcePath(cart.getSourceImage()));
				}
			}
		}
		
		return cartList;
	}
	/**
	 * 移除购物车信息通过购物车id
	 */
	@Override
	public void removeSourceBycartId(Integer cartId) {
		
		cartMapper.removeSourceBycartId(cartId);
		
	}
	/**
	 * 移除用户加入购物车的全部商品信息
	 */
	@Override
	public void removeSourceAllByUserId(Integer userId) {
		cartMapper.removeSourceAllByUserId(userId);
	}

}
